package com.shoulder.resourceserver.entrypoint;

import com.shoulder.core.utils.JsonUtils;
import com.shoulder.core.api.ApiResult;
import com.shoulder.core.utils.ValidateUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        String requestURI = request.getRequestURI();

        log.info("访问 {} 认证失败:{}", requestURI, authException.getMessage());

        ApiResult<Object> apiResult = ApiResult.badRequest();
        apiResult.setMsg("认证失败,身份凭证不可信");
        // 处理 OAuth2AuthenticationException
        if (authException instanceof OAuth2AuthenticationException exception) {
            OAuth2Error error = exception.getError();
            log.info("认证异常:{}", error.getErrorCode());
            boolean match = ValidateUtils.isChinese(error.getErrorCode());
            apiResult.setMsg(match ? error.getErrorCode() : "认证异常");
        }

        if (authException instanceof InvalidBearerTokenException exception) {
            OAuth2Error error = exception.getError();
            log.info("Bearer Token 信息异常:{}", error.getErrorCode());
            boolean match = ValidateUtils.isChinese(error.getErrorCode());
            apiResult.setMsg(match ? error.getErrorCode() : "Bearer Token 信息异常");
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtils.obj2Json(apiResult));
        writer.flush();
        writer.close();
    }
}